package ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.swing.Box;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;

import control.SystemControl;
import control.SystemUIControl;
import jpcap.NetworkInterface;
import middlelayer.PacketBuffer;
import sniff.pack.CommonPacket;
import ui.widget.ShowPromptDialog;
import ui.widget.TxtPanel;
import ui.widget.XPanel;
import ui.widget.YPSearchInputPanel;
import ui.widget.YPUIBtn;
import util.SearchUtil;

public class FuncPanel extends XPanel {
	private static FuncPanel self;
	private YPUIBtn startStopBtn;
	private YPUIBtn cleanBtn;
	private JComboBox<String> networkInterfaceSelector;
	private YPSearchInputPanel searchInput;
	private int currentNetworkInterfaceSelectorIndex;

	private FuncPanel() {
		startStopBtn = new YPUIBtn("开始");
		cleanBtn = new YPUIBtn("清除缓存");
		searchInput = new YPSearchInputPanel(500, 50);
		currentNetworkInterfaceSelectorIndex = 0;
		NetworkInterface[] nt = SystemControl.getDeviceList();
		String[] lsitData = new String[nt.length];
		for (int i = 0; i < lsitData.length; i++) {
			lsitData[i] = nt[i].description;
		}
		Color miColor = new Color(255, 80, 80);
		networkInterfaceSelector = new JComboBox<>(lsitData);
		networkInterfaceSelector.setMaximumSize(new Dimension(400, 35));
		networkInterfaceSelector.setPreferredSize(new Dimension(400, 35));
		networkInterfaceSelector.addItemListener((e) -> {
			if (e.getStateChange() == ItemEvent.SELECTED) {
				int index = networkInterfaceSelector.getSelectedIndex();
				if (index != currentNetworkInterfaceSelectorIndex) {
					int value = JOptionPane.showConfirmDialog(null, "更改网卡将删除所有捕获到的数据包，是否继续？", "提示！",
							JOptionPane.YES_NO_CANCEL_OPTION);
					if (value == 0) {
						currentNetworkInterfaceSelectorIndex = index;
						if (!SystemControl.changeDevice(SystemControl.getDeviceList()[index])) {
							ShowPromptDialog.showMessage("选择网卡失败，未知原因");
						} else {
							ShowPromptDialog.showMessage("网卡已更改");
						}
					}

				}
			}
		});
		startStopBtn.addActionListener((e) -> {
			if (startStopBtn.getText().equals("开始")) {
				SystemControl.startSniff();
			} else {
				SystemControl.stopSniff();
			}
		});

		searchInput.getFindButton().addActionListener((e) -> {
			searchBtnActionEvent();
		});

		cleanBtn.addActionListener((e) -> {
			int value = JOptionPane.showConfirmDialog(null, "将删除所有捕获到的数据包，是否继续？", "提示！",
					JOptionPane.YES_NO_CANCEL_OPTION);
			if (value == 0) {
				SystemControl.stopSniff();
				PacketBuffer.cleanAll();
				PacketBuffer.cleanShow();
				SystemUIControl.showPackets();
				ShowPromptDialog.showMessage("已删除");
			}
		});

		cleanBtn.setDefaultColor(Color.RED);
		cleanBtn.setMouseInColor(miColor);
		add(Box.createHorizontalStrut(30));
		add(startStopBtn);
		add(Box.createHorizontalStrut(30));
		add(cleanBtn);
		add(Box.createHorizontalStrut(40));
		add(searchInput);
		add(Box.createHorizontalStrut(50));
		add(new TxtPanel(60, 35, "选择网卡:"));
		add(networkInterfaceSelector);
	}

	private CommonPacket getSimplePack() {
		byte[] head = new byte[20];
		byte[] data = "HTTP/1.1dlkjadsklfjaskljfklajflasj".getBytes();
		for (int i = 0; i < 20; i++) {
			byte b = Byte.parseByte(i + "");
			byte c = Byte.parseByte(i + 20 + "");
			head[i] = b;
		}
		CommonPacket pack = new CommonPacket("1", "2", "3", 4, "5", head, data);
		return pack;
	}

	private void searchBtnActionEvent() {
		String values = searchInput.getFindInput().getText();
		String[] cmds = values.split(";");
		if (values.trim().length() == 0 || cmds.length == 0) {
			SystemUIControl.showAllPack();
			return;
		}
		List<CommonPacket> result = Collections.synchronizedList(new ArrayList<>());
		for (String tcmd : cmds) {
			tcmd = tcmd.toUpperCase().trim();
			String[] param = null;
			String cmd = tcmd;
			if (tcmd.contains(":")) {
				cmd = tcmd.substring(0, tcmd.indexOf(":"));
				String params = tcmd.substring(tcmd.indexOf(":") + 1, tcmd.length());
				param = params.split(",");
				for (int i = 0; i < param.length; i++) {
					param[i] = param[i].trim().replaceAll("\r\n", "");
				}
			}
			for (CommonPacket pack : PacketBuffer.getAllPackets()) {
				switch (cmd) {
				case "ARP":
				case "IPV4":
				case "IPV6":
				case "HTTP":
				case "OSPF":
				case "TCP":
				case "UDP":
				case "ICMP":
					if (SearchUtil.isOnlyProcotolCmd(cmd, pack)) {
						result.add(pack);
					}
					break;
				case "IP":
					if (SearchUtil.isOnlyProcotolCmd("IPV4", pack)||SearchUtil.isOnlyProcotolCmd("IPV6", pack)) {
						result.add(pack);
					}
					break;
				case "TCP.PORT":
					if (SearchUtil.isTcpPortCmd(param, pack)) {
						result.add(pack);
					}
					break;
				case "UDP.PORT":
					if (SearchUtil.isUdpPortCmd(param, pack)) {
						result.add(pack);
					}
					break;
				case "IP.ADDR":
					if (SearchUtil.isIpAddrCmd(param, pack)) {
						result.add(pack);
					}
					break;
				case "IPV4.ADDR":
					if (SearchUtil.isIpv4AddrCmd(param, pack)) {
						result.add(pack);
					}
					break;
				case "IPV6.ADDR":
					if (SearchUtil.isIpv6AddrCmd(param, pack)) {
						result.add(pack);
					}
					break;
				case "MAC":
					if (SearchUtil.isMacCmd(param, pack)) {
						result.add(pack);
					}
					break;
				case "ARP.IP":
					if (SearchUtil.isArpIpCmd(param, pack)) {
						result.add(pack);
					}
					break;
				case "ARP.MAC":
					if (SearchUtil.isArpMacCmd(param, pack)) {
						result.add(pack);
					}
					break;
				default:
					ShowPromptDialog.showMessage("不正确的表达式：" + cmd);
					return;
				}
			}
		}
		PacketBuffer.setShowPackets(result);
		SystemUIControl.showPackets();
	}

	public YPUIBtn getStartStopBtn() {
		return startStopBtn;
	}

	public void setStartStopBtn(YPUIBtn startStopBtn) {
		this.startStopBtn = startStopBtn;
	}

	public YPUIBtn getCleanBtn() {
		return cleanBtn;
	}

	public void setCleanBtn(YPUIBtn cleanBtn) {
		this.cleanBtn = cleanBtn;
	}

	public JComboBox<String> getNetworkInterfaceSelector() {
		return networkInterfaceSelector;
	}

	public void setNetworkInterfaceSelector(JComboBox<String> networkInterfaceSelector) {
		this.networkInterfaceSelector = networkInterfaceSelector;
	}

	public YPSearchInputPanel getSearchInput() {
		return searchInput;
	}

	public void setSearchInput(YPSearchInputPanel searchInput) {
		this.searchInput = searchInput;
	}

	public int getCurrentNetworkInterfaceSelectorIndex() {
		return currentNetworkInterfaceSelectorIndex;
	}

	public void setCurrentNetworkInterfaceSelectorIndex(int currentNetworkInterfaceSelectorIndex) {
		this.currentNetworkInterfaceSelectorIndex = currentNetworkInterfaceSelectorIndex;
	}

	public static FuncPanel getInstance() {
		if (self == null) {
			self = new FuncPanel();
		}
		return self;
	}

}
